package com.hdax.dm.rabbitmq;

import cn.hutool.core.bean.BeanUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@RabbitListener(queues = {"dmsms"})
@Component
@Slf4j
public class RabbitSMSListener {


    private static final String ACCESSKEY_ID = "LTAI4Fi6Dyp85rtARLMG1WoB";
    private static final String ACCESSKEY_SECRET = "3qu7gkF1ZQqJ8bh4lWMgLewUkq48ks";
    private static final String TEMPLATE_CODE = "SMS_180346654";
    private static final String SIGN_CODE = "邯郸翱翔";

    @RabbitHandler
    public String sendSms(Map<String,String> messageInfo){
        try {
            send(messageInfo);
        } catch (Exception e) {
            log.error("短信发送失败");
            throw new RuntimeException(e);
        }
        return null;
    }

    private Map<String, Object> send(Map<String,String> params) throws Exception {
        Config config = new Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(ACCESSKEY_ID)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(ACCESSKEY_SECRET);
        Client client = new Client(config);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        // 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(params.get("phoneNumber"))
                .setSignName(SIGN_CODE)
                .setTemplateCode(TEMPLATE_CODE)
                .setTemplateParam("{\"code\":\""+params.get("vcode")+"\"}");
        RuntimeOptions runtime = new RuntimeOptions();
        Map<String,Object> map = new HashMap<>();
        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            map = BeanUtil.beanToMap(sendSmsResponse,false,false);
        } catch (TeaException error) {
            // 如有需要，请打印 error
            Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            Common.assertAsString(error.message);
        }
        return map;
    }
}
